package com.teamwork.module03.util;

import com.teamwork.common.entity.common.User;
import com.teamwork.common.util.RedisUtil;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Component
public class EmailUtil {

    @Resource
    private  JavaMailSender sender;
    @Resource
    private RedisUtil redisUtil;
    public  void  sendCode(User user, String toemail){


        //将该验证码保存到redis中去

        String username = user.getUsername();
        send(username,toemail);

        //先把用户信息也保存到redis中去
        //存放一天，一天后自动清除
        redisUtil.set("register:"+username,user,24*60*60*1000);
    }

    public void send(String username,String toemail){
        //四位数
        int code = (int) ((Math.random()*9+1)*1000);
        String codes = String.valueOf(code);
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("【注册验证码】验证消息");
        message.setText("注册验证:你本次的验证码为:"+codes+"  有效期为3分钟。");
        message.setTo(toemail);
        message.setFrom("1046407954@qq.com");

        sender.send(message);
        redisUtil.set("code:"+username,codes,3*60*1000);

    }




}
